let fsModule = require('fs');
let pathModule = require('path');

function handleUrl(pathname, res) {
    let currentPath = __dirname;
    console.log(`dirname:${__dirname}`);
    let ppath = currentPath.substr(0, currentPath.length - 11);
    if (!pathname || pathname === "/" || pathname.endsWith("/index.html")) {
        pathname = "/src/index.html";
    }
    pathname = ppath + pathname;
    console.log(`pathname:${pathname}`);
    fsModule.exists(pathname, (exists) => {
        console.log(`fileExists:${exists}`);
        if (exists) {
            switch (pathModule.extname(pathname)) {
                case ".html":
                    res.writeHead(200, {
                        "Content-Type": "text/html"
                    });
                    break;
                case ".js":
                    res.writeHead(200, {
                        "Content-Type": "text/javascript"
                    });
                    break;
                case ".css":
                    res.writeHead(200, {
                        "Content-Type": "text/css"
                    });
                    break;
                default:
                    res.writeHead(200, {
                        "Content-Type": "application/octet-stream"
                    });
            }

            fsModule.readFile(pathname, (err, data) => {
                res.end(data);
            });
        }
    });
}

exports.handleUrl = handleUrl;